#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : index.py
@Author  : different
@Time    : 2021-8-5 15:48
@Desc    :

"""
import logging

from flask import render_template, jsonify, redirect, url_for, g, request

from apps.models.charts import DataSourceTitle
from apps.models.user import User
from apps.view import index_bp
from expand import db, login_required, auth_management


# 蓝图容器


@index_bp.route('/')
def start():
    # redirect url_for 路由要加蓝图名称
    return redirect(url_for('index.index'))


@index_bp.route('/index')
@login_required
def index():
    # 获取数据列表
    if g.user.is_superuser:
        table = DataSourceTitle.query.filter_by(is_delete=False).all()
    else:
        table = DataSourceTitle.query.filter(DataSourceTitle.is_delete == False,
                                             DataSourceTitle.users.any(User.id == g.user.id))
    return render_template('index.html', table=table)


@index_bp.route('/del/<pk>', methods=['PUT'])
@login_required
@auth_management
def delete(pk):
    DataSourceTitle.query.filter_by(id=pk).update(dict(is_delete=True))
    db.session.commit()
    return jsonify(data='删除成功'), 200


@login_required
@auth_management
@index_bp.route('/distribute/<pk>', methods=['GET', 'POST'])
def distribute(pk):
    table = DataSourceTitle.query.filter_by(id=pk).first()
    if request.method == 'GET':
        # 所有用户
        users = User.query.with_entities(User.nickname, User.id).filter_by(is_superuser=0).all()
        users = [{'value': i[1], 'name': i[0]} for i in users]
        return render_template('distribute.html', users=users, pk=pk, table=table)
    user_id = request.json.get('user_id')
    user = User.query.filter_by(id=user_id).first()

    try:
        table.users.append(user)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(code=500, msg="Error")
    return jsonify(code=200, msg="Success")
